package com.zhf.cloud.gateway.springcloudgateway.advice;

import com.alibaba.fastjson.JSONObject;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 曾鸿发
 * @create: 2021-11-18 17:47
 * @description：异常处理类
 **/
@Slf4j
@RestController
public class ExceptionHandlerAdvice {

    /**
     * 这是此项目的Exception 的message格式，不同exception对应的message格式不一样
     * @param exception
     * @return
     */
    public Map<String, Object> feignException(FeignException exception){
        int httpStatus = exception.status();
        if(httpStatus >= HttpStatus.INTERNAL_SERVER_ERROR.value()){
            log.error("feign调用异常", exception);
        }

        Map<String, Object> data = new HashMap<>();

        String msg = exception.getMessage();

        if(!StringUtils.isEmpty(msg)){
            int index = msg.indexOf("\n");
            if(index > 0){
                String string = msg.substring(index);
                if(!StringUtils.isEmpty(string)){
                    JSONObject json = JSONObject.parseObject(string.trim());
                    data.putAll(json.getInnerMap());
                }
            }
        }

        if(data.isEmpty()){
            data.put("message", msg);
        }
        data.put("code", httpStatus + "");
        return data;
    }

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, Object> badRequestException(IllegalArgumentException exception){
        Map<String, Object> data = new HashMap<>();
        data.put("code", HttpStatus.BAD_REQUEST.value());
        data.put("message", exception.getMessage());
        return data;
    }
}
